import axios from "axios";
import Cookies from "js-cookie";

/**
 * 数据请求
 * @param {string} uri
 * @param {object} params
 */
export function pipeline(url, params, opt = {}) {
  const headers = new Headers();
  headers.append("X-Requested-With", "XMLHttpRequest");
  headers.append("Accept", "*/*");
  // headers.append('Content-Type', 'application/x-www-form-urlencoded')
  return axios({
    url,
    credentials: "include",
    method: "post",
    headers,
    data: parseBody(params),
    ...opt
  });
}

/**
 * 请求参数处理
 * @param {object} params
 */
export function parseBody(params = {}) {
  params = {
    ...params,
    ticket: Cookies.get("ticket")
  };
  const formData = new FormData();
  Object.keys(params).forEach(key => {
    formData.append(
      key,
      params[key] instanceof Blob ? params[key] : String(params[key]) || ""
    );
  });
  return formData;
}
